package com.bsoft.gol.hcs.clinical.dao;


import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.StatelessSession;
import pcn.prescribe.OdsPrescriptionDrug;

import java.util.List;


public abstract class OdsPrescriptionDrugDAO extends HibernateSupportDelegateDAO<OdsPrescriptionDrug> {
    @DAOMethod(sql = "from OdsPrescriptionDrug where prescriptionInfoId =:prescriptionInfoId")
    public abstract List<OdsPrescriptionDrug> findByInfoId(@DAOParam("prescriptionInfoId")String prescriptionInfoId);

    public OdsPrescriptionDrugDAO() {
        this.setKeyField("prescriptionDrugId");
    }
    @DAOMethod(sql = "from OdsPrescriptionDrug where prescriptionInfoId =:prescriptionInfoId")
    public abstract List<OdsPrescriptionDrug> findDrugByPrescriptionInfoId(@DAOParam("prescriptionInfoId") String prescriptionInfoId);

    @DAOMethod(sql = "from OdsPrescriptionDrug where prescriptionInfoId =:prescriptionInfoId and drugId =:drugId")
    public abstract List<OdsPrescriptionDrug> findDrugByDrugId(@DAOParam("prescriptionInfoId") String prescriptionInfoId,
                                                               @DAOParam("drugId") String drugId);

    public List<OdsPrescriptionDrug> findPrescriptionDrug(final OdsPrescriptionDrug drug){
        HibernateStatelessResultAction<List<OdsPrescriptionDrug>> action = new AbstractHibernateStatelessResultAction<List<OdsPrescriptionDrug>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("select * from ods_prescription_drug where org_id = '" + drug.getOrgId()+"' and  prescription_info_id = '" + drug.getPrescriptionInfoId()+"' ");

                if (StringUtils.isNotEmpty(drug.getOrgDrugId())) {
                    stringBuffer.append(" and org_drug_id = '" + drug.getOrgDrugId()+"'");
                }
                SQLQuery sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                sqlQuery.addEntity(OdsPrescriptionDrug.class);
                setResult(sqlQuery.list());
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
}
